const WebSocket = require("ws");

// 创建一个 WebSocket 服务器，监听端口 8080
const wss = new WebSocket.Server({ port: 8080 });

console.log("WebSocket chat server is running on ws://localhost:8080");

// 广播消息给所有客户端
function broadcast(message, sender) {
  wss.clients.forEach((client) => {
    if (client !== sender && client.readyState === WebSocket.OPEN) {
      client.send(message);
    }
  });
}

wss.on("connection", (ws) => {
  console.log("A new user joined the chat!");

  // 通知所有用户有新用户加入
  broadcast("A new user has joined the chat.", ws);

  // 当收到消息时
  ws.on("message", (message) => {
    console.log(`Received message: ${message}`);
    // 广播消息给所有用户
    // 如果是字符类型，websocket会返回字符类型给客户端
    // 如果是字节类型，websocket会返回字节类型给客户端
    broadcast(message.toString(), ws);
  });

  // 当用户断开连接时
  ws.on("close", () => {
    console.log("A user left the chat.");
    // 通知所有用户有用户离开
    broadcast("A user has left the chat.", ws);
  });
});